﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using HRM.HRMServiceProxy;
using System.IO;
using HRM.Utilities;
using System.Runtime.InteropServices;
using HRM.BusinessLogic;
namespace HRM

{
    public partial class frmEmployee_QTChucDanh : DockContent
    {
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        EmployeeClient _wcfEmployee;
        string _InsBookNo = "";
        bool _IsLoaded = false;

        public frmEmployee_QTChucDanh()
        {
            InitializeComponent();
            _wcfEmployee = Service.Employee();
            txtKeyWord.Focus();
            this.KeyPreview = true;
            AddColumnEmployeeGrid();
            AddColumnChucDanh();
            LoadEmployeeData();
            dgvUser.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void AddColumnChucDanh()
        {
            if (dgvQTBHXH.ColumnCount <= 0)
            {
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_WorkUnit", UpdateUI.GetString("donvilamviec"), "", 150, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_FromDate", "Từ tháng", "C", 80, true, true);
                //--UISetting.AddColumn(ref dgvPremium_QTBHXH, "Premium_ToDate", "Đến tháng", "C", 80, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_ToDate_Chuan", "Đến tháng", "C", 80, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "LoaiPs", "Loại", "C", 60, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_Job", UpdateUI.GetString("nghenghiep"), "", 100, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_Salary", "ML", "R", 70, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_BasicFactor", "HSL", "R", 60, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_PositionFactor", "HS Cvụ", "R", 60, true, true);

                UISetting.AddColumn(ref dgvQTBHXH, "Premium_SeniorityFactorPercent", "% TNNghề", "R", 60, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_SeniorityFactor", "HS TNNghề", "R", 60, true, true);

                UISetting.AddColumn(ref dgvQTBHXH, "Premium_OverSeniorityFactorPercent", "% TNVK", "R", 60, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_OverSeniorityFactor", "HS TNVK", "R", 60, true, true);

                UISetting.AddColumn(ref dgvQTBHXH, "Premium_AreaFactor", "HS KV", "R", 60, false, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_MonthNo", "Số tháng", "R", 60, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "PA", "PA", "R", 60, true, true);
                UISetting.AddColumn(ref dgvQTBHXH, "Premium_Description", UpdateUI.GetString("ghichu"), "", 100, false, true);
            }
        }

        private void LoadEmployeeData()
        {
            DataSet ds = _wcfEmployee.Employee_GetList(out itemCount, Program.intBranchID, 0, UISetting.GetKeyWord(txtKeyWord.Text.Trim()), "", "", currPage, pageSize);
            int n = ds.Tables[0].Rows.Count;
            dgvUser.Rows.Clear();
            PageIndex();
            for (int i = 0; i < n; i++)
            {
                if (!Globals.Object_GetValue<bool>(ds.Tables[0].Rows[0]["Employee_IsQuited"]))
                {
                    dgvUser.Rows.Insert(i, 1);
                    dgvUser.Rows[i].Cells["Employee_SIBookNo"].Value = ds.Tables[0].Rows[i]["Employee_SIBookNo"].ToString();
                    dgvUser.Columns["Employee_FullName"].Frozen = true;
                    dgvUser.Rows[i].Cells["RowNumber"].Value = ds.Tables[0].Rows[i]["RowNumber"].ToString();
                    dgvUser.Rows[i].Cells["Employee_ID"].Value = ds.Tables[0].Rows[i]["Employee_ID"].ToString();
                    dgvUser.Rows[i].Cells["Employee_Code"].Value = ds.Tables[0].Rows[i]["Employee_Code"].ToString();
                    dgvUser.Rows[i].Cells["Employee_FullName"].Value = ds.Tables[0].Rows[i]["Employee_FullName"].ToString();
                    
                    if (ds.Tables[0].Rows[i]["Employee_DateOfBirth"] != DBNull.Value)
                        dgvUser.Rows[i].Cells["Employee_DateOfBirth"].Value = Convert.ToDateTime(ds.Tables[0].Rows[i]["Employee_DateOfBirth"]).ToString("dd/MM/yyyy");
                    else
                        dgvUser.Rows[i].Cells["Employee_DateOfBirth"].Value = "";
                    dgvUser.Rows[i].Cells["Employee_Sex"].Value = ds.Tables[0].Rows[i]["Employee_Sex"].ToString();
                }
            }
            _IsLoaded = true;
        }

        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void AddColumnEmployeeGrid()
        {
            if (dgvUser.ColumnCount <= 0)
            {
                UISetting.AddColumn(ref dgvUser, "Employee_ID", "Mã chính", "", 1, false, true);
                UISetting.AddColumn(ref dgvUser, "RowNumber", UpdateUI.GetString("stt"), "C", 30, true, true);
                UISetting.AddColumn(ref dgvUser, "Employee_SIBookNo", "Số sổ BH", "L", 100, true, true);
                UISetting.AddColumn(ref dgvUser, "Employee_Code", UpdateUI.GetString("maso"), "", 120, false, true);
                UISetting.AddColumn(ref dgvUser, "Employee_FullName", UpdateUI.GetString("hovaten"), "", 150, true, true);
                UISetting.AddColumn(ref dgvUser, "Employee_Sex", "GT", "C", 50, true, true);
                UISetting.AddColumn(ref dgvUser, "Employee_DateOfBirth", UpdateUI.GetString("ngaysinh"), "C", 90, true, true);
            }
        }

        private void dgvUser_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvUser.SelectedCells.Count > 0)
            {
                _InsBookNo = dgvUser.Rows[dgvUser.SelectedCells[0].RowIndex].Cells["Employee_SIBookNo"].Value.ToString();
                LoadQTBH(_InsBookNo, Program.strBranchCode);
            }
        }

        private void LoadQTBH(string _InsBookNo, string _BranchCode)
        {
            FormGlobals.App_ProgressShow(delegate()
            {
                try
                {
                    DataTable dt = new DataTable();
                    PremiumClient _wcfPremium = Service.Premium();
                    int _opt = 0;
                    dt = _wcfPremium.Premium_QTBH(Program.strBranchCode, _InsBookNo, _opt, DateTime.MinValue, DateTime.MaxValue, 0).Tables[0];
                    dgvQTBHXH.Rows.Clear();
                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            dgvQTBHXH.Rows.Insert(i, 1);
                            dgvQTBHXH.Rows[i].Cells["Premium_WorkUnit"].Value = dt.Rows[i]["Premium_WorkUnit"].ToString();
                            dgvQTBHXH.Rows[i].Cells["Premium_FromDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_FromDate"]).ToString("MM/yyyy");
                            //--dgvPremium_QTBHXH.Rows[i].Cells["Premium_ToDate"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_ToDate"]).ToString("MM/yyyy");
                            dgvQTBHXH.Rows[i].Cells["Premium_ToDate_Chuan"].Value = Convert.ToDateTime(dt.Rows[i]["Premium_ToDate_Chuan"]).ToString("MM/yyyy");
                            dgvQTBHXH.Rows[i].Cells["LoaiPs"].Value = dt.Rows[i]["LoaiPs"].ToString();
                            dgvQTBHXH.Rows[i].Cells["Premium_Job"].Value = dt.Rows[i]["Premium_Job"].ToString();
                            dgvQTBHXH.Rows[i].Cells["Premium_Salary"].Value = dt.Rows[i]["Premium_Salary"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_Salary"]).ToString("#,##0");
                            dgvQTBHXH.Rows[i].Cells["Premium_BasicFactor"].Value = dt.Rows[i]["Premium_BasicFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_BasicFactor"]).ToString("#0.0##");
                            dgvQTBHXH.Rows[i].Cells["Premium_PositionFactor"].Value = dt.Rows[i]["Premium_PositionFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_PositionFactor"]).ToString("#0.0##");

                            dgvQTBHXH.Rows[i].Cells["Premium_SeniorityFactor"].Value = dt.Rows[i]["Premium_SeniorityFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_SeniorityFactor"]).ToString("#0.0##");

                            dgvQTBHXH.Rows[i].Cells["Premium_OverSeniorityFactor"].Value = dt.Rows[i]["Premium_OverSeniorityFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_OverSeniorityFactor"]).ToString("#0.0##");

                            dgvQTBHXH.Rows[i].Cells["Premium_AreaFactor"].Value = dt.Rows[i]["Premium_AreaFactor"] == DBNull.Value ? "0" : Convert.ToDecimal(dt.Rows[i]["Premium_AreaFactor"]).ToString("#0.0##");
                            if (dt.Rows[i]["Premium_MonthNo"].ToString() != "0")
                                dgvQTBHXH.Rows[i].Cells["Premium_MonthNo"].Value = dt.Rows[i]["Premium_MonthNo"].ToString();
                            else
                                dgvQTBHXH.Rows[i].Cells["Premium_MonthNo"].Value = (UISetting.GetMonth(Convert.ToDateTime(dt.Rows[i]["Premium_FromDate"]), Convert.ToDateTime(dt.Rows[i]["Premium_ToDate_Chuan"])) + 1).ToString();

                            string PA = dt.Rows[i]["Detail_InsTypeCode"].ToString();
                            PA = "ON,TS,OF".IndexOf(PA) > 0 ? PA : "";
                            dgvQTBHXH.Rows[i].Cells["PA"].Value = PA;
                            dgvQTBHXH.Rows[i].Cells["Premium_Description"].Value = dt.Rows[i]["Premium_Description"].ToString();
                            if (dgvQTBHXH.Rows[i].Cells["Premium_WorkUnit"].Value.ToString() == "")
                            {
                                dgvQTBHXH.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                                dgvQTBHXH.Rows[i].DefaultCellStyle.SelectionBackColor = Color.Yellow;
                            }

                            //Tính % nghề, vk

                            decimal BasicFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_BasicFactor"].Value.ToString());
                            decimal PosionFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_PositionFactor"].Value.ToString());
                            decimal OverFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_OverSeniorityFactor"].Value.ToString());
                            decimal JobFactor = UISetting.GetDecimalNo(dgvQTBHXH.Rows[i].Cells["Premium_SeniorityFactor"].Value.ToString());
                            //
                            if (OverFactor != 0)
                            {
                                decimal OverFactor_Percent = (OverFactor * 100 / BasicFactor);
                                dgvQTBHXH.Rows[i].Cells["Premium_OverSeniorityFactorPercent"].Value = Math.Round(OverFactor_Percent).ToString();
                            }
                            if (JobFactor != 0)
                            {
                                decimal JobFactor_Percnet = (JobFactor * 100 / (BasicFactor + PosionFactor + OverFactor));
                                dgvQTBHXH.Rows[i].Cells["Premium_SeniorityFactorPercent"].Value = Math.Round(JobFactor_Percnet).ToString();
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
                }
            }, "Lấy dữ liệu");
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            _IsLoaded = false;
            LoadEmployeeData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
            {
                currPage++;
            }
            _IsLoaded = false;
            LoadEmployeeData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage > 0)
                currPage--;
            _IsLoaded = false;
            LoadEmployeeData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
                currPage = totalPage - 1;
            _IsLoaded = false;
            LoadEmployeeData();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            currPage = 0;
            _IsLoaded = false;
            LoadEmployeeData();
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    btnSearch_Click(null, null);
                    break;
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvUser.SelectedCells.Count > 0)
            {
                _InsBookNo = dgvUser.Rows[dgvUser.SelectedCells[0].RowIndex].Cells["Employee_SIBookNo"].Value.ToString();
                frmEmployee_QTChucDanh_Edit frm = new frmEmployee_QTChucDanh_Edit(_InsBookNo);

                //frm.ShowDialog();

                frm.Show(this);
                //if (frm.Show_Form() == DialogResult.OK)
                //{
                //    btnSearch_Click(null, null);
                //}
            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            frmTime f = new frmTime(1);
            string fileName = "MauEpChucDanh.xls";

            if (f.ShowDialog(this) == DialogResult.OK)
            {
                DataTable dtChucDanh = Employee_Controller.Instance().Employee_DSChuDanhExcel(
                        Program.strBranchCode
                        ,f.FromDate
                        ,f.ToDate
                        );
                try
                {
                    if (dtChucDanh.Rows.Count > 0)
                    {
                        ExportData2Excel(dtChucDanh, Path.GetTempPath() + "\\" + fileName);

                        try
                        {
                            System.Diagnostics.Process.Start(Path.GetTempPath() + "\\" + fileName);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Không mở được File \n" + Path.GetTempPath() + "\\" + fileName, "Thông báo");
                        }
                    }
                    else
                        Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), "Không có dữ liệu!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("File " + Path.GetTempPath() + "\\" + fileName + " đang được mở bằng một ứng dụng khác.\nHãy chọn file khác!", "Thông báo");
                }
            }
        }

        private void ExportData2Excel(DataTable dt, string _FileName)
        {
            DataTable dtEx = new DataTable();
            //Xây dựng các cột trước
            DataColumn column;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                column = new DataColumn(dt.Columns[i].ColumnName, typeof(string));
                column.Caption = dt.Columns[i].Caption;
                dtEx.Columns.Add(column);
            }
            //Gán dữ liệu vào các dòng tương ứng theo cột
            DataRow dr;
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                dr = dtEx.NewRow();

                //Liệt kê các cột theo thứ tự côt của bảng gốc, kết hợp gán dữ liệu dòng tương ứng cột
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    if(dt.Columns[k].DataType ==  typeof(String))
                        dr[k] = UnicodeConvert.UnicodeToTCVN3(dt.Rows[j][k].ToString());
                    else
                        dr[k] = dt.Rows[j][k];
                }
                dtEx.Rows.InsertAt(dr, j);
            }

            //

            ReadExcelFile.exportDataToExcel(dtEx, _FileName);
        }

        private void btnEditMulti_Click(object sender, EventArgs e)
        {
            frmEmployee_NhapChucDanh frm = new frmEmployee_NhapChucDanh();
            frm.Show_Form();
        }
    }
}
